package cn.ekuma.epos.catalog;

import javax.swing.JPanel;

import com.openbravo.bean.Product;
import com.openbravo.pos.bean.ProductExt;
import com.openbravo.pos.panels.event.ProductChangedListener;
import com.openbravo.pos.panels.model.ProductViewTableModel;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

public class JProductListPanel extends JPanel {
	private javax.swing.JScrollPane jScrollPane1;
	protected org.jdesktop.swingx.JXTable jXTable1;
	CatelogManager manager;
	private ProductViewTableModel tableModel;
	private ProductChangedListener productChangedListener;
	
	public JProductListPanel(CatelogManager manager) {
		this.manager=manager;
		initComponents();
		tableModel=new ProductViewTableModel();
		jXTable1.setModel(tableModel);
		jXTable1.addMouseListener(new MouseAdapter(){
			@Override
			public void mouseClicked(MouseEvent e) {
				int selectVCol=jXTable1.getSelectedRow();
				if(e.getClickCount()==2&&selectVCol>-1){
					fireProductChanged(tableModel.getObj(jXTable1.convertRowIndexToModel(selectVCol)));
				}else if(e.getClickCount()==1&&selectVCol>-1){
					fireProductSelected(tableModel.getObj(jXTable1.convertRowIndexToModel(selectVCol)));
				}
			}

	    });
		jXTable1.setRequestFocusEnabled(false);
		jXTable1.setFocusable(false);
	}
	
	
	private void initComponents() {
		jScrollPane1 = new javax.swing.JScrollPane();
	    jXTable1 = new org.jdesktop.swingx.JXTable();
	    setLayout(new java.awt.BorderLayout());
	    jScrollPane1.setViewportView(jXTable1);
	    add(jScrollPane1, java.awt.BorderLayout.CENTER);
	}

	public void reflush(){
		List<Product> changed=new ArrayList<Product>();
		for(ProductExt p:manager.getProducts())
			changed.add(p);
		tableModel.resert(changed);
	}
	
	public void  addProductChangedListener(ProductChangedListener l){
		listenerList.add(ProductChangedListener.class, l);
	}
	
	public void removeProductChangedListener(ProductChangedListener l){
		listenerList.remove(ProductChangedListener.class, l);
	}
	
	public void fireProductChanged(Product obj){
		for(ProductChangedListener l:listenerList.getListeners(ProductChangedListener.class))
			l.baseBeanChanged(obj, obj);	 
	}
	
	public void setProductChangedListener(ProductChangedListener l){
		this.productChangedListener=l;
	}
	
	private void fireProductSelected(Product obj) {
		productChangedListener.baseBeanChanged(obj, obj);
	}
}
